package mcom.xmks.bluetooth.mesh;

import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.wch.meshlib.core.MeshServer;
import cn.wch.meshlib.frame.MeshFrameAssemble;
import io.reactivex.Emitter;
import mcom.xmks.bluetooth.mesh.adapter.NodeListAdapter;
import mcom.xmks.bluetooth.mesh.base.AbstractActivity;
import mcom.xmks.bluetooth.mesh.constant.IntentConstant;
import mcom.xmks.bluetooth.mesh.core.DataModel;
import mcom.xmks.bluetooth.mesh.storage.GroupStorageUtil;
import mcom.xmks.bluetooth.mesh.storage.NodeItem;
import mcom.xmks.bluetooth.mesh.utils.ConvertUtil;
import mcom.xmks.bluetooth.mesh.utils.LogTool;

public class GroupDetailActivity extends AbstractActivity {

    private EditText etNodeData,editReceive;
    private SwipeRecyclerView rvNode;
    private Button btnSendData;
    private SwitchCompat swHex;
    private TextView tvLabel;

    private Intent intent=null;
    private String groupName=null;
    private int groupAddress=-1;
    private NodeListAdapter adapter;
    private List<NodeItem> nodesInGroup=new ArrayList<>();
    @Override
    protected void setView() {
        setContentView(R.layout.activity_group_detail);
        intent=this.getIntent();
        if(intent.hasExtra(IntentConstant.GROUP_NET_NAME)){
            groupName=intent.getStringExtra(IntentConstant.GROUP_NET_NAME);
        }
        groupAddress=intent.getIntExtra(IntentConstant.GROUP_NET_ADDRESS,-1);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            if(groupName!=null)
                actionBar.setTitle(groupName);
            actionBar.setSubtitle(String.format(Locale.getDefault(),"组地址:%04X",groupAddress));
            actionBar.setHomeButtonEnabled(true);  //启用返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true); //显示返回按钮
        }
        etNodeData=this.findViewById(R.id.etNodeData);
        editReceive=this.findViewById(R.id.editReceive);
        swHex=this.findViewById(R.id.swHex);
        btnSendData=this.findViewById(R.id.btnSendData);
        rvNode=this.findViewById(R.id.rvNode);
        tvLabel=this.findViewById(R.id.tvLabel);
    }

    @Override
    protected void initWidget() {
        //接收侦听
        MeshFrameAssemble.getInstance().setDataListener((data, len) -> {
           String hex= ConvertUtil.fromByteArray2HexString(data);
           String d=editReceive.getText().toString();
            editReceive.setText(d==null||d.length()==0?(hex):(d + "\n"+hex));
        });
        adapter=new NodeListAdapter(new NodeListAdapter.OnClickListener() {
            @Override
            public void onClick(int netAddress, String name) {
            }
            @Override
            public void onLongClick(int netAddress, String name) {
            }
        });
        rvNode.setSwipeMenuCreator((leftMenu, rightMenu, position) -> {
            SwipeMenuItem menu=new SwipeMenuItem(this)
                    .setText("删除")
                    .setBackgroundColor(Color.RED)
                    .setWidth(200)//菜单宽度
                    .setHeight(RecyclerView.LayoutParams.MATCH_PARENT);//菜单高度
            rightMenu.addMenuItem(menu);
        });
        rvNode.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            if(menuBridge!=null)
              menuBridge.closeMenu();
            //左菜单还是右菜单
            int direction=menuBridge.getDirection();
            //菜单里item的下标
            int position=menuBridge.getPosition();
            LogTool.d(String.valueOf(direction+ position+ adapterPosition));
            if(direction==-1 && position==0){
                deleteNodeFromGroup(adapterPosition);
            }
        });
        rvNode.setAdapter(adapter);
        rvNode.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvNode.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        btnSendData.setOnClickListener(v -> {
            sendData();
        });
        loadGroupDetail();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_group_detail,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case  android.R.id.home:
                onBackPressed();
                break;
            case  R.id.deleteGroup:
                deleteGroup();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogTool.d("GroupDetailActivity destroy");
    }

    /**
     * 重新加载Group下的各个节点
     */
    public void loadGroupDetail(){
        if(groupAddress>-1){
            nodesInGroup=GroupStorageUtil.getNodesInGroup(groupAddress);
            tvLabel.setVisibility(nodesInGroup.size()==0? View.GONE:View.VISIBLE);
            adapter.loadAllNodes(nodesInGroup);
        }
    }
    private void sendData(){
        if(groupAddress<0){
            LogTool.d("groupAddress address is null or negative");
            return;
        }
        String dataString = etNodeData.getText().toString();
        if(dataString.isEmpty()){
            showToast("内容为空");
            return;
        }
        byte[] data;
        if(swHex.isChecked()){
            try {
                data=ConvertUtil.fromHexString2ByteArray(dataString);
            } catch (Exception e) {
                showToast(e.getMessage());
                return;
            }
        }else{
            data=dataString.getBytes(StandardCharsets.UTF_8);
        }
        DataModel.getInstance().rxjavaExecute(this, "正在发送数据", new DataModel.CallbackRunnable<>() {
            @Override
            public Boolean onRunnable() {
                try {
                    return MeshServer.getInstance().transferData(groupAddress, data); //这里应该采用异步处理
                } catch (Exception e) {
                    return null;
                }
            }
        }, new Emitter<Boolean>() {
            @Override
            public void onNext(Boolean value) {
                showToast("发送数据"+(value?"成功" : "失败"));
            }
            @Override
            public void onError(Throwable e) {
                showToast(e.getMessage());
            }
            @Override
            public void onComplete() {
            }
        });
    }
    private void deleteNodeFromGroup(int pos){
        if(groupAddress==-1){
            return;
        }
       NodeItem nodeItem = nodesInGroup.get(pos);
        DataModel.getInstance().rxjavaExecute(this, "从Group中删除节点", new DataModel.CallbackRunnable<>() {
            @Override
            public Boolean onRunnable() {
                try {
                  return   MeshServer.getInstance().cancelSubscribe(nodeItem.getNodeAddress(),groupAddress);
                } catch (Exception e) {
                   return null;
                }
            }
        }, new Emitter<Boolean>() {
            @Override
            public void onNext(Boolean value) {
                showToast("取消订阅"+ (value?"成功" : "失败"));
                if(value) {
                    GroupStorageUtil.removeNodeFromGroup(nodeItem.getNodeAddress(), groupAddress);
                    loadGroupDetail();
                }
            }
            @Override
            public void onError(Throwable e) {
                showToast(e.getMessage());
            }
            @Override
            public void onComplete() {
            }
        });
    }
    private void deleteGroup(){
        if(groupAddress==-1){
            return;
        }
       List<NodeItem> nodesInGroup = GroupStorageUtil.getNodesInGroup(groupAddress);
        if(nodesInGroup==null)
            return;
        if(nodesInGroup.size()!=0){
            showToast("请先删除Group下的节点");
            return;
        }else{
            GroupStorageUtil.deleteGroup(groupAddress);
            showToast("删除成功");
            onBackPressed();
        }
    }
}